<?php
namespace admin;
use lmonkey\CatTree as CT;
use models\BaseDao;
use Slince\Upload\UploadHandlerBuilder;
use JasonGrimes\Paginator;
class Product extends Admin{
    public function  __construct(){
        parent::__construct();
        $this->assign('menumark','product');

        $db = new BaseDao();

        // 获取全部商品分类,按照ord排序
        $data = $db->select('category',['id','catname','pid','ord']);

        $tree = CT::getList($data);
        
        // 将数据全部分给模板
        $this->assign('cats',$tree);
    }
/**
 * 产品列表页面
 */
    function index(){
        // 获取数据库操作对象
        $db = new BaseDao();

        // 分页
        $num = $_GET['num'] ?? 1;

        // $prosql['ORDER'] = ['id'=>'DESC'];
        $where = [];

        if(isset($_GET['state']) && $_GET['state'] !=''){
            $where['state'] = $_GET['state'];
            $state = '&state='.$_GET['state'];
        }

        if(!empty($_GET['cid']) || $_GET['cid'] != 0){
            $where['cid'] = $_GET['cid'];
            $cid = '&cid='.$_GET['cid'];
        }
        
        if(!empty($_GET['name'])){
            $where['name[~]'] = $_GET['name'];
            $name = '&name='.$_GET['name'];
        }
        
        if(!empty($_GET['filter']) || $_GET['filter'] != ''){
            list($filed,$value) = explode('|',$_GET['filter']);
            $where[$filed] = $value;
            $filter = '&filter='.$_GET['filter'];
        }
        
        if(!empty($_GET['orderby']) || $_GET['orderby'] != ''){
            list($filed,$value) = explode('|',$_GET['orderby']);

            $prosql['ORDER'][$filed] = [$value];
            $orderby = '&orderby='.$_GET['orderby'];

        }else{
            $prosql['ORDER'] = ['id'=>'DESC'];
        }

        $this->assign('get',$_GET);


        $totalItems = $db->count('product',$where);
       
        $itemsPerPage = PNUM;
        $currentPage = $num;
        $urlPattern = '/admin/product?num=(:num)'.$state.$cid.$name.$filter.$orderby;

        $paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

        $start = ($currentPage-1) * $itemsPerPage;
        $prosql['LIMIT'] = [$start,$itemsPerPage];
        $prosql = array_merge($prosql,$where);

        // 获取全部产品,按照ord排序
        // $data = $db->select('product','*',$prosql);
        $data = $db->select('product','*',$prosql);
        // 将数据全部分给模板
        $this->assign('data',$data);
        $this->assign('fpage',$paginator);



        // 过滤的数据
        $filter_arr = ['istuijian|1'=>'推荐商品','istj|1'=>'特价商品','wlmoney|0'=>'包邮商品','num|0'=>'售空商品'];
        $this->assign('filter_arr',$filter_arr);

        $orderby_arr["clicknum|desc"] = '浏览量(多到少)';
        $orderby_arr["clicknum|asc"] = '浏览量(少到多)';

        $orderby_arr["sellnum|desc"] = '销售量(多到少)';
        $orderby_arr["sellnum|asc"] = '销售量(少到多)';

        $orderby_arr["num|desc"] = '库存量(多到少)';
        $orderby_arr["num|asc"] = '库存量(少到多)';

        $orderby_arr["collectnum|desc"] = '收藏数(多到少)';
        $orderby_arr["collectnum|asc"] = '收藏数(少到多)';

        $orderby_arr["asknum|desc"] = '咨询数(多到少)';
        $orderby_arr["asknum|asc"] = '咨询数(少到多)';

        $orderby_arr["commentnum|desc"] = '评价数(多到少)';
        $orderby_arr["commentnum|asc"] = '评价数(少到多)';

        $this->assign('orderby_arr',$orderby_arr);


        //标题    
        $this->assign('title','产品列表');
        // 导入模板
        $this->display('product/index');
    }
    function add(){
        // 如果$_POST['do_submit]存在,说明是添加动作
        if(isset($_POST['do_submit'])){

            
            // 上传图片
            $path = TEMPDIR."/uploads/product";
            $builder = new UploadHandlerBuilder(); //create a builder.
            $handler = $builder
            //add constraints
            ->allowExtensions(['jpg','png','gif'])
            ->allowMimeTypes(['image/*'])

            ->saveTo($path) //save to local
            ->getHandler();

            $files = $handler->handle();
            $filename = $files['logo']->getUploadedFile()->getClientOriginalName(); // original name

            $newfilename = date('Y-md') . '-' . uniqid() . '.' . $files['logo']->getUploadedFile()->getClientOriginalExtension();

            rename($path.'/'.$filename,$path.'/'.$newfilename);            

            $_POST['logo'] = $newfilename;

            $_POST['istj'] = isset($_POST['istj']) ? 1 : 0;

            $db = new BaseDao();


            $_POST['atime'] = empty($_POST['atime']) ? time() :strtotime($_POST['atime']);


            unset($_POST['do_submit']);

            if($db->insert('product',$_POST)){
                $this->success('/admin/product','添加ok');
            }else{
                $this->error('/admin/product/add','添加fail');
            }
        }
        //标题    
        $this->assign('title','添加产品');
        $this->display('product/add');

    }


    function mod($id){
        $db = new BaseDao();
        $this->assign($db->get('product','*',['id'=>$id]));
        $this->assign('title',"修改产品");
        $this->display('product/mod');
    }


    function doupdate(){

        if($_FILES['logo']['error'] == 0){
            // 上传图片
            $path = TEMPDIR."/uploads/product";
            $builder = new UploadHandlerBuilder(); //create a builder.
            $handler = $builder
            //add constraints
            ->allowExtensions(['jpg','png','gif'])
            ->allowMimeTypes(['image/*'])

            ->saveTo($path) //save to local
            ->getHandler();

            $files = $handler->handle();
            $filename = $files['logo']->getUploadedFile()->getClientOriginalName(); // original name

            $newfilename = date('Y-md') . '-' . uniqid() . '.' . $files['logo']->getUploadedFile()->getClientOriginalExtension();

            rename($path.'/'.$filename,$path.'/'.$newfilename);            

            $_POST['logo'] = $newfilename;

        }


        $id = $_POST['id'];
        unset($_POST['id']);

        $_POST['atime'] = empty($_POST['atime']) ? time() :strtotime($_POST['atime']);
        $_POST['istj'] = isset($_POST['istj']) ? 1 : 0;


        $db = new BaseDao();

        if($db->update('product',$_POST,['id'=>$id])){
            $this->success('/admin/product','修改ok');
        }else{
            $this->error('/admin/product/mod/'.$id,'修改fail');
        }
    }


    function del($id){
        $db = new BaseDao();

        if($db->delete('product',['id'=>$id])){
            $this->success('/admin/product','删除ok');
        }else{
            $this->error('/admin/product','删除fail');
        }
    }


    function alldel(){
        $db = new BaseDao();
        $num = 0;
        foreach($_POST['id'] as $id){
            
            $num += $db->delete('product',['id'=>$id]);
        }
        if($num > 0){
            $this->success('/admin/product',$num.'篇产品删除ok');
        }else{
            $this->success('/admin/product','删除失败');
        }
    }


    function state($state){
        
        $db = new BaseDao();
        $num = 0;
        foreach($_POST['id'] as $id){
            
            $num += $db->update('product',['state'=>$state],['id'=>$id]);
            
        }

        $mess = ['下架','上架'];

        if($num > 0){
            $this->success('/admin/product',$num.'个产品'.$mess[$state].'ok');
        }else{
            $this->success('/admin/product','批量'.$mess[$state].'失败');
        }
    }


    function tuijian($tuijian){
        
        $db = new BaseDao();
        $num = 0;
        foreach($_POST['id'] as $id){
            
            $num += $db->update('product',['istuijian'=>$tuijian],['id'=>$id]);
            
        }

        $mess = ['取消推荐','推荐'];

        if($num > 0){
            $this->success('/admin/product',$num.'个产品'.$mess[$tuijian].'ok');
        }else{
            $this->success('/admin/product','批量'.$mess[$tuijian].'失败');
        }
    }
}